package api

import (
	"net/http"
	"runtime"
	"time"

	"github.com/gin-gonic/gin"
)

type HomeHandler struct {
	startTime time.Time
}

func NewHomeHandler() *HomeHandler {
	return &HomeHandler{
		startTime: time.Now(),
	}
}

// Home godoc
// @Summary Get server status
// @Description Get the current status of the server
// @Tags home
// @Accept json
// @Produce json
// @Success 200 {object} HomeResponse
// @Router / [get]
func (h *HomeHandler) Home(c *gin.Context) {
	var m runtime.MemStats
	runtime.ReadMemStats(&m)

	status := HomeResponse{
		Status:       "running",
		Version:      "1.0.0", // 你可以根据实际情况修改版本号
		Uptime:       time.Since(h.startTime).String(),
		GoVersion:    runtime.Version(),
		MemoryUsage:  bToMb(m.Alloc),
		NumGoroutine: runtime.NumGoroutine(),
	}

	c.JSON(http.StatusOK, status)
}

type HomeResponse struct {
	Status       string `json:"status"`
	Version      string `json:"version"`
	Uptime       string `json:"uptime"`
	GoVersion    string `json:"go_version"`
	MemoryUsage  uint64 `json:"memory_usage_mb"`
	NumGoroutine int    `json:"num_goroutine"`
}

func bToMb(b uint64) uint64 {
	return b / 1024 / 1024
}

func RegisterHomeRoutes(r *gin.Engine) {
	homeHandler := NewHomeHandler()
	r.GET("/", homeHandler.Home)
}
